package com.lyy.utils;

import org.aspectj.lang.ProceedingJoinPoint;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.sql.Connection;
import java.sql.SQLException;

/**
 * 通知类
 */
@Component
public class TransactionManager {

    @Autowired
    private ConnectionUtils connectionUtils;

    public void startTransaction(){
        Connection connection = connectionUtils.getConnection();
        try {
            System.out.println("开启事务");
            connection.setAutoCommit(false);
        } catch (SQLException e) {
            e.printStackTrace();
            throw new RuntimeException("开启事务失败,"+e.toString());
        }
    }

    /**
     * 提交事务
     */
    public void commit(){
        Connection connection = connectionUtils.getConnection();
        try {
            System.out.println("提交事务");
            connection.commit();
        } catch (SQLException e) {
            e.printStackTrace();
            throw new RuntimeException("提交事务失败,"+e.toString());
        }
    }

    /**
     * 回滚事务
     */
    public void rollBack(){
        Connection connection = connectionUtils.getConnection();
        try {
            System.out.println("业务异常,事务回滚");
            connection.rollback();
        } catch (SQLException e) {
            e.printStackTrace();
            throw new RuntimeException("回滚事务失败,"+e.toString());
        }
    }

    /**
     * spring aop的环绕通知,手动控制增强代码的执行时机
     * @param proceedingJoinPoint
     * @return
     */
    public Object around(ProceedingJoinPoint proceedingJoinPoint){
        Object returnValue=null;
        try {
            //开启事务
            startTransaction();
            Object[] args = proceedingJoinPoint.getArgs();
            returnValue = proceedingJoinPoint.proceed(args);
            //提交事务
            commit();
        } catch (Throwable throwable) {
            throwable.printStackTrace();
            //回滚事务
            rollBack();
        } finally {
            //最终通知
        }
        return returnValue;
    }
}
